<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\web\UploadedFile;

/**
 * This is the model class for table "event".
 *
 * @property int $id
 * @property string $title
 * @property string $alias
 * @property string $description
 * @property string $content
 * @property string $date_start
 * @property string $date_end
 * @property string $time_start
 * @property string $pub_date
 * @property string $prev_img
 * @property string $gallery_img
 * @property int $id_type
 * @property int $id_price
 * @property int $request
 *
 * @property EventPrice $price
 * @property Department $parentDepartment
 * @property EventType $type
 */
class Event extends \yii\db\ActiveRecord
{
    public $imageForCover;
    public $imagesForGallery;
    public $casArr;
    
    const BUCKET_NAME = 'ogikm-img-event';

    const KASSIR_TYPE_A = 'A'; 

    const RARS_0 = '0+';
    const RARS_6 = '6+';
    const RARS_12 = '12+';
    const RARS_16 = '16+';
    const RARS_18 = '18+';

    const DEFAULT_COVER = 'https://storage.yandexcloud.net/ogikm-cdn/vksp-default-cover.jpg';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'event';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'alias', 'id_type', 'id_price'], 'required'],
            [['title', 'alias'], 'trim'],
            [['content'], 'string'],
            [['date_start', 'date_end', 'pub_date'], 'safe'],
            [['id_type', 'id_price', 'request', 'is_pushkart', 'is_main_event', 'id_info_chanel', 'is_free', 'id_organization_branch'], 'integer'],
            [['title', 'alias', 'description', 'gallery_img', 'kassir_bo_id', 'kassir_bo_type', 'rars_info'], 'string', 'max' => 255],
            [['schedule_str'], 'string', 'max' => 512],
            [['time_start', 'prev_img'], 'string', 'max' => 45],
            [['id_price'], 'exist', 'skipOnError' => true, 'targetClass' => EventPrice::className(), 'targetAttribute' => ['id_price' => 'id']],
            [['id_type'], 'exist', 'skipOnError' => true, 'targetClass' => EventType::className(), 'targetAttribute' => ['id_type' => 'id']],
            [['imageForCover'], 'file', 'extensions' => 'jpg'],
            [['imagesForGallery'], 'file', 'extensions' => 'jpg', 'maxFiles' => 20],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'pub_date',
                'updatedAtAttribute' => false,
                'value' => new Expression('NOW()'),
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_info_chanel' => 'Канал информации',
            'title' => 'Название событие',
            'alias' => 'Псевдоним',
            'description' => 'Краткое описание',
            'content' => 'Содержимое',
            'date_start' => 'Дата начала',
            'date_end' => 'Дата завершения',
            'time_start' => 'Время начала',
            'pub_date' => 'Дата внесения в базу',
            'prev_img' => 'Обложка',
            'gallery_img' => 'Галерея',
            'id_type' => 'Тип',
            'id_price' => 'Ценовая категория',
            'request' => 'По запросу',
            'imageForCover' => 'Изображение для обложки',
            'imagesForGallery' => 'Изображения для галлереи',
            'kassir_bo_id' => 'КассирРу (ID мероприятия)',
            'kassir_bo_type' => 'КассирРу (тип)',
            'is_pushkart' => 'Доступно по Пушкинской карте',
            'schedule_str' => 'Расписание (строкой)',
            'rars_info' => 'Возрастная классификация',
            'is_main_event' => 'Главное событие',
            'is_free' => 'Бесплатно',
            'id_organization_branch' => 'Филиал',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPrice()
    {
        return $this->hasOne(EventPrice::className(), ['id' => 'id_price']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getType()
    {
        return $this->hasOne(EventType::className(), ['id' => 'id_type']);
    }

    public function getInfoChanel()
    {
        return $this->hasOne(InfoChanel::className(), ['id' => 'id_info_chanel']);
    }

    public function getOrganizationBranch()
    {
        return $this->hasOne(OrganizationBranch::className(), ['id' => 'id_organization_branch']);
    }

    public function getSales()
    {
        return $this->hasMany(TicketSales::className(), ['event_id' => 'id']);
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        if($this->prev_img)
        {
            $this->deleteImageFile($this->prev_img);
        }

        if($this->gallery_img)
        {
            foreach(explode(',', $this->gallery_img) as $image)
            {
                $this->deleteImageFile($image);
            }
        }
        
        return true;
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        if($insert)
        {
            if($this->imageForCover)
            {
                $this->processCoverImage();   
            }
            if(!empty($this->imagesForGallery))
            {
                $this->processGalleryImages();
            }
        }
        else
        {
            if($this->imageForCover)
            {
                if($this->prev_img)
                {
                    $this->deleteImageFile($this->prev_img);
                }
                $this->processCoverImage();
            }
            if(!empty($this->imagesForGallery))
            {
                $this->processGalleryImages();
            }
        }
        
        return true;
    }

    private function deleteImageFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }

    public function deleteImageFromGallery($imageName)
    {
        $this->deleteImageFile($imageName);
        $this->gallery_img = implode(',', array_diff(explode(',', $this->gallery_img), [$imageName]));
    }

    public function processCoverImage()
    {
        $generatedName = $this->generateFileName($this->imageForCover, 'c');
        $this->prev_img = $generatedName;
        $this->uploadImage($this->imageForCover, $generatedName);
    }

    public function processGalleryImages()
    {
        if($this->gallery_img)
        {
            $generatedNamesArr = explode(',', $this->gallery_img);
        }
        else
        {
            $generatedNamesArr = array();
        }
        
        foreach ($this->imagesForGallery as $index => $image) 
        {
            $generatedName = $this->generateFileName($image, $index);
            array_push($generatedNamesArr, $generatedName);
            $this->uploadImage($image, $generatedName);
        }

        $this->gallery_img = implode(',', $generatedNamesArr);
    }

    private function uploadImage($file, $fileName)
    {
        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
        }
    }

    private function generateFileName($file, $postfix = '')
    {
        return uniqid() . $postfix . '.' . $file->extension;
    }
}
